package nl.hanze.web.t41.http;

import java.io.*;

public class HTTPHandlerImpl implements HTTPHandler {

	private int returnCode = 500;
	private File file; // the requested file
	private HTTPRequest request;
	private HTTPResponse response;
	private HTTPHeader header;
	
	private DirectoryAuth dirAuth;

	public HTTPHandlerImpl() {
//		this.webRoot = webRoot;
		dirAuth = new SimpleAuth();
	}

	public void handleRequest(InputStream in, OutputStream out) {
		// recieve http headers
		request = new HTTPRequest(in, HTTPServer.webRoot); // request file
		
		if (!request.isPageRequest())
			return;
		
		System.out.println("Requested file: " + request.getPath()); // write path to terminal for debug
		
		file = new File(HTTPServer.webRoot.getPath() + HTTPServer.dirSep + request.getPath()); // the requested file
		
		// if file has no extension go to index.html
		if (getFileEXT(file) == "") {
			file = new File(HTTPServer.webRoot.getPath() + HTTPServer.dirSep +
					request.getPath() + HTTPServer.dirSep + "index.html");
			if(!file.exists()) { // if index.html does not exist then make file index.htm
				file = new File(HTTPServer.webRoot.getPath() + HTTPServer.dirSep +
						request.getPath() + HTTPServer.dirSep + "index.htm");
				request.appendToPath("index.htm");
			} else {
				request.appendToPath("index.html");
			}
			System.out.println("File is now: " + file.getPath());
		}
		
		// check if file type is supported
		if (getFileType() > 4) {
			System.out.println("File: " + file.getPath() + " NOT implemented");
			returnCode = 501;
		} else {
			// check per directory whether path exists and needs authorization
			String[] dirs = request.getPath().split("/");
			String subPath = HTTPServer.webRoot.getPath();
			for (int n = 0; n <= dirs.length; n++) {
				file = new File(subPath);
				if (!file.exists()) {
					returnCode = 404;
					break;
				}
				if (file.isDirectory() && dirAuth.requiresAuthorization(file)) {
					if (!request.hasCredentials() || 
							!dirAuth.authorize(file, request.getUsername(), request.getPassword())) {
						returnCode = 401;
						break;
					}
				}
				if (n < dirs.length)
					subPath += HTTPServer.dirSep + dirs[n];
				else {
					returnCode = 200;
				}
			}
		}
		
		if (returnCode != 200)
			file = ErrorPages.getPageForError(returnCode);
		
		header = new HTTPHeader(returnCode, getFileType(), file);
		response = new HTTPResponse(out, header, file); // response to browser
	}

	
	/*
	 * the file type (return code can be found in HTTPHeader class)
	 */
	public int getFileType(){

		int return_code = 5; // not supported return_code
				
		if(file.getPath().endsWith(".html") || file.getPath().endsWith(".htm") || file.getPath().endsWith(".css") || file.getPath().endsWith(".js") || file.getPath().endsWith(".txt") || file.getPath().endsWith(".pdf")){
			return_code = 0;
		} else if(this.file.getPath().endsWith(".jpeg")){
			return_code = 1;
		} else if(this.file.getPath().endsWith(".jpg")){
			return_code = 2;
		} else if(this.file.getPath().endsWith(".gif")){
			return_code = 3;
		} else if(this.file.getPath().endsWith(".png")){
			return_code = 4;
		} 
		
		return return_code;
	}
	
	/*
	 * get the file extension
	 */
	public String getFileEXT(File file){
		String extension = "";
		String filename = file.getPath();
		int dotPos = filename.lastIndexOf(".");
		if(dotPos != -1){
  	      	extension = filename.substring(dotPos);
		}
		  
		return extension;
	}
}
